package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.ExchangeListNewAdapter;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.CoinShopData;
import com.kkd.kkdapp.http.entity.CoinShopDataItem;
import com.kkd.kkdapp.http.entity.ExchangeRecordItem;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.Time_Date;
import com.kkd.kkdapp.view.CountView;
import com.kkd.kkdapp.view.KkdXlistView;
import com.kkd.kkdapp.view.KkdXlistView.KKDScrollListener;

public class MyHappyBiNewActivity extends BaseActivity implements
		OnClickListener, KKDScrollListener {

	private static final int SUCCESS_REQUEST = 0;
	private static final int FAIL_REQUEST = 1;

	private Context mContext = this;
	private RelativeLayout happyBiRecord_top_img_back;
	private KkdXlistView happyBiRecord_lv;
	private ListView mListView;
	private ExchangeListNewAdapter adapter;
	private List<ExchangeRecordItem> totalList = new ArrayList<ExchangeRecordItem>();
	private ImageView image_null;
	private TextView tv_null;
	private boolean REFRESHFLAG = false;
	private CountView tv_num_happyBi_head;
	private RelativeLayout happy_currency_task;
	private Intent intent;
	private DecimalFormat df = new DecimalFormat("#,###");
	private TextView tv_tip_null;
	private List<CoinShopDataItem> list = new ArrayList<CoinShopDataItem>();
	private String happyShopUrl;// 快乐币商店url
	private RelativeLayout rel_toHappiShop_head;
	private String coinMisUrl; // 快乐币任务url
	private RelativeLayout myHappyBiNew_tv_howto; // 如何获得
	private boolean isShowToastOnRefresh = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SUCCESS_REQUEST:
				if (adapter == null) {
					adapter = new ExchangeListNewAdapter(mContext, list,
							tv_num_happyBi_head);
					mListView.setAdapter(adapter);
				}
				CoinShopData data = (CoinShopData) msg.obj;
				// 快乐币数量
				tv_num_happyBi_head.showNumberWithAnimation(0,
						data.getCoinCount(), 1000);
				// 设置快乐币商店
				if (data.getHappyShop().getHappyShopFlag() == 1) {
					happyShopUrl = data.getHappyShop().getHappyShopUrl();
					rel_toHappiShop_head.setVisibility(View.VISIBLE);
				} else {
					rel_toHappiShop_head.setVisibility(View.GONE);
				}
				coinMisUrl = data.getHappyShop().getCoinMisUrl();
				if (TextUtils.isEmpty(coinMisUrl)) {
					myHappyBiNew_tv_howto.setVisibility(View.VISIBLE);
					happy_currency_task.setVisibility(View.GONE);
				} else {
					happy_currency_task.setVisibility(View.VISIBLE);
					myHappyBiNew_tv_howto.setVisibility(View.GONE);
				}

				// 设置兑换列表
				list.clear();
				list.addAll(data.getDataList());
				adapter.notifyDataSetChanged();
				if (list == null || list.size() == 0) {
					tv_tip_null.setVisibility(View.VISIBLE);
				} else {
					tv_tip_null.setVisibility(View.GONE);
				}
				happyBiRecord_lv.stopLoadMore(1);
				happyBiRecord_lv.stopRefresh();
				Time_Date time_Date = new Time_Date();
				String time = time_Date.get_Year_Day();
				happyBiRecord_lv.setRefreshTime(time);

				image_null.setVisibility(View.GONE);
				tv_null.setVisibility(View.GONE);

				if (!isShowToastOnRefresh) {
					isShowToastOnRefresh = true;
				}
				break;

			case FAIL_REQUEST:
				happyBiRecord_lv.stopLoadMore(1);
				happyBiRecord_lv.stopRefresh();

				if ((list == null || list.size() == 0) && adapter == null) {
					image_null.setImageResource(R.drawable.img_null_net);
					if (msg.arg1 == KkdHttpClient.NO_NET) {
						tv_null.setText("网络错误，请稍候下拉刷新重试");
					} else {
						tv_null.setText("服务异常，请稍候下拉刷新重试");
					}
					image_null.setVisibility(View.VISIBLE);
					tv_null.setVisibility(View.VISIBLE);
				}
				if (isShowToastOnRefresh) {
					String desc = (String) msg.obj;
					if (!TextUtils.isEmpty(desc)) {
						AppUtil.makeToastForCustomer(mContext, desc);
					}
				} else {
					isShowToastOnRefresh = true;
				}
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_happy_bi_new);
		initView();
		setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		initData();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (adapter != null) {
			adapter.destroyDialog();
		}
	}

	private void initData() {
		requestCoin();
		// if (AppUtil.isConnect(mContext)) {
		// requestCoin();
		// } else {
		// happyBiRecord_lv.stopLoadMore(1);
		// happyBiRecord_lv.stopRefresh();
		// if (!REFRESHFLAG) {
		// if (totalList == null || totalList.size() == 0) {
		// image_null.setImageResource(R.drawable.img_null_net);
		// tv_null.setText("网络错误，请稍候下拉刷新重试");
		// image_null.setVisibility(View.VISIBLE);
		// tv_null.setVisibility(View.VISIBLE);
		// happyBiRecord_lv.stopRefresh();
		// } else {
		// showToast("网络错误，请稍候下拉刷新重试");
		// happyBiRecord_lv.stopLoadMore(1);
		// happyBiRecord_lv.stopRefresh();
		// }
		// }
		// }
	}

	private void initView() {
		/*
		 * 初始化头部view
		 */
		View headView = LayoutInflater.from(mContext).inflate(
				R.layout.head_myhappybi, null);
		// 快乐币数量
		tv_num_happyBi_head = (CountView) headView
				.findViewById(R.id.tv_num_happyBi_head);
		tv_num_happyBi_head.setDecimalFormat(new DecimalFormat("#,###"));
		// 查看明细
		RelativeLayout linear_toDetail = (RelativeLayout) headView
				.findViewById(R.id.rel_toDetail);
		linear_toDetail.setOnClickListener(this);
		// 前往快乐币商城
		rel_toHappiShop_head = (RelativeLayout) headView
				.findViewById(R.id.rel_toHappiShop_head);
		rel_toHappiShop_head.setOnClickListener(this);
		// 提示
		tv_tip_null = (TextView) headView.findViewById(R.id.tv_tip_null);
		/*
		 * 初始化view
		 */
		happyBiRecord_top_img_back = (RelativeLayout) findViewById(R.id.happyBiRecord_top_img_back);
		happyBiRecord_lv = (KkdXlistView) findViewById(R.id.happyBiRecord_lv);
		image_null = (ImageView) findViewById(R.id.id_no_content);
		tv_null = (TextView) findViewById(R.id.id_no_content_text);
		happy_currency_task = (RelativeLayout) findViewById(R.id.happy_currency_task);
		happyBiRecord_lv.setKKDScrollListener(this);
		mListView = happyBiRecord_lv.mListView;
		mListView.setDividerHeight(0);
		mListView.addHeaderView(headView);
		happyBiRecord_lv.startRefresh();
		myHappyBiNew_tv_howto = (RelativeLayout) this
				.findViewById(R.id.myHappyBiNew_tv_howto);
	}

	private void setListener() {
		happyBiRecord_top_img_back.setOnClickListener(this);
		happy_currency_task.setOnClickListener(this);
		myHappyBiNew_tv_howto.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.happyBiRecord_top_img_back:
			finish();
			break;

		case R.id.happy_currency_task:
			if (!TextUtils.isEmpty(coinMisUrl)) {
				SystemUtils.onEvent("Account_HappyCoin_HowToEarn", 1);
				intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("url", coinMisUrl);
				startActivity(intent);
			}
			break;

		case R.id.rel_toDetail:
			SystemUtils.onEvent("Account_HappyCoin_Detail", 1);
			intent = new Intent(mContext, MyHappyBiDetailActivity.class);
			startActivity(intent);
			break;

		case R.id.rel_toHappiShop_head:
			SystemUtils.onEvent("Account_HappyCoin_GoToHappyMarket", 1);
			intent = new Intent(mContext, KKDWebActivity.class);
			intent.putExtra("titleName", "快乐商城");
			intent.putExtra("url", happyShopUrl);
			intent.putExtra("coinMisUrl", coinMisUrl);
			startActivity(intent);
			break;
		case R.id.myHappyBiNew_tv_howto:
			SystemUtils.onEvent("Account_HappyCoin_HowToEarn", 1);
			intent = new Intent(mContext, HowToHappyCoinActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	public void onRefresh() {
		REFRESHFLAG = true;
		initData();
	}

	@Override
	public void onLoadMore() {
		// if (AppUtil.isConnect(mContext)) {
		// pageNO++;
		// REFRESHFLAG = false;
		// }
		REFRESHFLAG = false;
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				happyBiRecord_lv.stopLoadMore(-1);
				happyBiRecord_lv.stopRefresh();
			}
		});
	}

	// 请求快乐币商店接口
	private void requestCoin() {
		happyBiRecord_lv.setNoMore(false);
		String customerIdAndToken = PreferenceUtils.getInstance()
				.getcustomerId(mContext);
		String[] cat = customerIdAndToken.split("&");
		if (cat == null || cat.length < 2)
			return;
		KkdHttpMagager.getInstance().coinShopList(CoinShopData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						CoinShopData data = (CoinShopData) responseBody;
						Message msg = Message.obtain();
						msg.what = SUCCESS_REQUEST;
						msg.obj = data;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = Message.obtain();
						msg.what = FAIL_REQUEST;
						msg.obj = desc;
						msg.arg1 = statusCode;
						mHandler.sendMessage(msg);
					}
				});
	}
}
